# -*- coding:utf-8 -*-

'''
Created on 2012-9-17

@author: jezhang
'''
from __future__ import unicode_literals, absolute_import
from datetime import timedelta
from django.contrib.auth.models import User
from django.utils import timezone
from lru import lru_cache_function
from disn.settings import  get_wechat_client, WECHAT_ADMIN_USER_ID
# import Cookie
import datetime
import logging
import urllib
import string
import random
import re
import pickle
from time import mktime

logging.info('module base reloaded')

#this is the key
ts="8ABC7DLO5MN6Z9EFGdeJfghijkHIVrstuvwWSTUXYabclmnopqKPQRxyz01234"

# encode the content, jia mi
def s52e(n):
    N  = len(ts)
    N2 = N * N
    N5 = N * 5
    nl = len(n)
    t  = []

    def m (y):
        t.append(ts[y])

    for x in range(nl):
        a = ord(n[x])
        if (a<N5):
            m(int(a/N)),
            m(a%N)
        else:
            m(int(a/N2) + 5)
            m(int(a/N)%N)
            m(a%N)
    s = ''.join(t)
    return str(len(str(len(s)))) + str(len(s)) + s


# decode the content, jie mi
def s52d (n):
    c = n[0]
    if not c.isdigit():
        return ''
    c = n[1:1+int(c)]
    if not c.isdigit():
        return ''
    c = int(c)

    nl = len(n)
    t  = []
    x  = len(str(c)) + 1

    def m (y) :
        return ts.index(n[y])

    N = len(ts)

    if (nl != x+c):
        return ''

    while (x<nl):
        a = m(x)
        x += 1
        if (a<5):
            f = a*N+m(x)
        else:
            f = (a-5)*N*N+m(x)*N+m(x+1)
            x+= 1

        t.append(chr(f))
        x+= 1

    return ''.join(t)

def gen_password(length=6):
    return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(length))

def gbk2utf8(vs):
    return vs.decode('gbk').encode('utf-8')

def to_utf8(vs):
    return vs.encode('utf-8')

def get_bj_time():
    return datetime.datetime.utcnow() + datetime.timedelta(hours=+8)

def urldecode(value):
    return  urllib.unquote(urllib.unquote(value)).decode('utf8')
    #return  urllib.unquote(value).decode('utf8')

def urlencode(value):
    return urllib.quote(value.encode('utf8'))

def sid():
    now=get_bj_time()
    return now.strftime('%Y%m%d%H%M%S')+str(now.microsecond)

def today_with_dash():
    return get_bj_time().strftime('%Y-%m-%d')

def today_with_slash():
    return get_bj_time().strftime('%Y/%m/%d')

def gen_timestamp():
    """generate current time in string format"""
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def get_current_hour():
    return get_bj_time().hour

def today():
#    now = datetime.datetime.date();
    return get_bj_time().strftime('%Y%m%d')
#    return time.strftime('%Y%m%d',time.localtime(time.time()))

def setWechatSubscribedStatus(vs,value):
    if value:
        return vs[:19] + '1'
    else:
        return vs[:19] + '0'
def getWechatSubscribedStatus(vs):
    if not vs:
        return False
    if len(vs) != 20:
        return False
    value = vs[19:]
    if value == '0':
        return False
    else:
        return True

def get_default_subscribed_status():
    return '00000000000000000000'

def filter_emoji(desstr,restr='\u25FD'):
    '''
    过滤表情
    '''
    try:
        co = re.compile('[\U00010000-\U0010ffff]')
    except re.error:
        co = re.compile('[\uD800-\uDBFF][\uDC00-\uDFFF]')
    return co.sub(restr, desstr)

def str_2_emoji(emoji_str):
    '''
    把字符串转换为表情
    '''
    if not emoji_str:
        return emoji_str
    h = HTMLParser.HTMLParser()
    emoji_str = h.unescape(h.unescape(emoji_str))
    #匹配u"\U0001f61c"和u"\u274c"这种表情的字符串
    co = re.compile(r"[\'\"]\\[Uu]([\w\"]{9}|[\w\"]{5})")
    pos_list=[]
    result=emoji_str
    #先找位置
    for m in co.finditer(emoji_str):
        pos_list.append((m.start(),m.end()))
    #根据位置拼接替换
    for pos in range(len(pos_list)):
        if pos==0:
            result=emoji_str[0:pos_list[0][0]]
        else:
            result=result+emoji_str[pos_list[pos-1][1]:pos_list[pos][0]]
        result = result +eval(emoji_str[pos_list[pos][0]:pos_list[pos][1]])
        if pos==len(pos_list)-1:
            result=result+emoji_str[pos_list[pos][1]:len(emoji_str)]
    return result

def display_request_meta(request):
    values = request.META.items()
    # values.sort()
    for k,v in values:
        print('%s ===> %s' %(k,v))

def get_client_ip(request):
    if request.META.has_key('HTTP_X_FORWARDED_FOR'):
        return  request.META['HTTP_X_FORWARDED_FOR']
    else:
        return request.META['REMOTE_ADDR']

def get_session_key(request):
    session_key = request.session.session_key;
    if session_key:
        return session_key
    else:
        return get_csrf_cookie(request)

def get_csrf_cookie(request):
    if request.META.has_key('CSRF_COOKIE'):
        return request.META['CSRF_COOKIE']
    else:
        return '%s%s' %(get_client_ip(request),today())

def get_client_browser(request):
    if request.META.has_key('HTTP_USER_AGENT'):
        return request.META['HTTP_USER_AGENT']

def get_http_referer(request):
    try:
        if get_client_browser(request).find('Mozilla/4.0') >= 0 and get_request_path(request).find('wechat') >= 0:
            return '微信公众号'
        if request.META.has_key('HTTP_REFERER'):
            return request.META['HTTP_REFERER']
    except:
        if request.META.has_key('HTTP_REFERER'):
            return request.META['HTTP_REFERER']
        else:
            return ''

def get_request_path(request):
    if request.META.has_key('PATH_INFO'):
        return '%s%s' %(request.META['HTTP_HOST'], request.META['PATH_INFO'])

def set_value(redis, name, value):
    redis.set(name, pickle.dumps(value))

def set_value_ex(redis, name, value, time):
    redis.setex(name=name, value=pickle.dumps(value), time=time)

def get_value(redis, key):
    pickled_value = redis.get(key)
    if pickled_value is None:
        return None
    return pickle.loads(pickled_value)

def get_date_range(aDate):
    return (datetime.datetime.combine(aDate, datetime.time.min),datetime.datetime.combine(aDate, datetime.time.max))

def get_today_date_range():
    today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)
    today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
    return(today_min,today_max)

def get_date_from_range(date_from):
    today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)
    return (datetime.datetime.combine(date_from, datetime.time.min),today_max)

def get_date_by_delta(aDate, num):
    delta = datetime.timedelta(days=num)
    return aDate + delta

def judge_pure_english(keyword):
    return all(ord(c) < 128 for c in keyword)


def delta2dict( delta ):
    """Accepts a delta, returns a dictionary of units"""
    delta = abs( delta )
    return {
        '年': int(delta.days / 365),
        '天': int(delta.days % 365),
        '小时': int(delta.seconds / 3600),
        '分钟': int(delta.seconds / 60) % 60,
        '秒': delta.seconds % 60,
        '毫秒': delta.microseconds
    }


def nature_time(dt, precision=2, past_tense='{}前', future_tense='{}后'):
    """Accept a datetime or timedelta, return a human readable delta string,
    Steal from ago.human
    """
    now = timezone.now().replace(microsecond=0)
    delta = dt
    if type(dt) is not type(timedelta()):
        delta = dt - now

    the_tense = future_tense
    if delta < timedelta(0):
        the_tense = past_tense

    d = delta2dict(delta)
    hlist = []
    count = 0
    units = ('年', '天', '小时', '分钟', '秒', '毫秒')
    for unit in units:
        if count >= precision:
            break  # met precision
        if d[unit] == 0:
            continue  # skip 0's
        if hlist and unit == units[-1]:  # skip X秒XX毫秒
            break
        hlist.append('%s%s' % (d[unit], unit))
        count += 1
    human_delta = ''.join(hlist)
    return the_tense.format(human_delta)


# @lru_cache_function(max_size=100, expiration=86400*2)  # cache for 2 days
def get_permanent_qrcode(scene_id):
    wechat_client = get_wechat_client()
    ticket = wechat_client.qrcode.create({
        'action_name': 'QR_LIMIT_SCENE',
        'action_info': {
            'scene': {'scene_id': scene_id},
        }
    })
    result = None
    if ticket:
        print('get_permanent_qrcode ticket created: %s' %ticket)
        result = {}
        result['ticket'] = ticket
        result['qrcode']   = wechat_client.qrcode.show(ticket)
    return result

# @lru_cache_function(max_size=100, expiration=86400*2)  # cache for 2 days
def get_permanent_qrcode_str(scene_str):
    wechat_client = get_wechat_client()
    ticket = wechat_client.qrcode.create({
        # 'expire_seconds': 2592000,
        'action_name': 'QR_LIMIT_STR_SCENE',
        'action_info': {
            'scene': {'scene_str': scene_str},
        }
    })
    result = None
    if ticket:
        print('get_permanent_qrcode_str ticket created: %s' %ticket)
        result = {}
        result['ticket'] = ticket
        result['qrcode']   = wechat_client.qrcode.show(ticket)
    return result

# @lru_cache_function(max_size=100, expiration=86400*2)  # cache for 2 days
def get_temporary_qrcode(scene_id, expire_seconds=2592000):
    wechat_client = get_wechat_client()
    ticket = wechat_client.qrcode.create({
        'expire_seconds': expire_seconds, # a month
        'action_name': 'QR_SCENE',
        'action_info': {
            'scene': {'scene_id': scene_id},
        }
    })
    result = None
    if ticket:
        print('get_temporary_qrcode ticket created: %s' %ticket)
        result = {}
        result['ticket'] = ticket
        result['qrcode']   = wechat_client.qrcode.show(ticket)
    else:
        print('get_temporary_qrcode failed')
    return result

# @lru_cache_function(max_size=100, expiration=86400*2)  # cache for 2 days
def get_temporary_qrcode_str(scene_str, expire_seconds=2592000):
    wechat_client = get_wechat_client()
    ticket = wechat_client.qrcode.create({
        'expire_seconds': expire_seconds, # a month
        'action_name': 'QR_STR_SCENE',
        'action_info': {
            'scene': {'scene_str': scene_str},
        }
    })
    result = None
    if ticket:
        print('get_temporary_qrcode_str ticket created: %s' %ticket)
        result = {}
        result['ticket'] = ticket
        result['qrcode']   = wechat_client.qrcode.show(ticket)
    return result

def get_or_create_admin():
    admin, admin_created = User.objects.get_or_create(username=WECHAT_ADMIN_USER_ID)
    # admin, admin_created = User.objects.create_superuser(WECHAT_ADMIN_USER_ID, 'test@test.com', 'pass')
    if admin_created:
        admin.set_password('pass')
        admin.save()
        print('created admin %s' %WECHAT_ADMIN_USER_ID)
    return admin

if __name__ == '__main__':
    print (gen_password())
    # print getWechatSubscribedStatus(get_default_subscribed_status())
    # print getWechatSubscribedStatus(setWechatSubscribedStatus(get_default_subscribed_status(),True))
    # print getWechatSubscribedStatus(setWechatSubscribedStatus(setWechatSubscribedStatus(get_default_subscribed_status(),True),False))
